package com.explorati.interview.interview.chapterfifteen.sort;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Random;

public class SortTestHelper<E extends Comparable<E>> {

	// 生成有n个元素的随机数组，范围在[rangeL,rangeR]
	public static Integer[] generateRandomArray(int n, int rangeL, int rangeR) {
		if (rangeL >= rangeR) {
			throw new IllegalArgumentException("Expect rangeL < rangeR ! ");
		}
		Random random = new Random();

		Integer[] arr = new Integer[n];
		for (int i = 0; i < n; i++) {
			arr[i] = random.nextInt((rangeR - rangeL + 1)) + rangeL;
		}
		return arr;
	}

	public static Integer[] generateNearlyOrderArray(int n, int swapTimes) {
		Integer[] arr = new Integer[n];
		for (int i = 0; i < n; i++) {
			arr[i] = i;
		}

		Random rand = new Random();
		for (int i = 0; i < swapTimes; i++) {
			int x = rand.nextInt(n);
			int y = rand.nextInt(n);
			int temp = arr[x];
			arr[x] = arr[y];
			arr[y] = temp;
		}

		return arr;
	}

	public static void printArray(Integer[] arr) {
		for (Integer i : arr) {
			System.out.print(i + "\t");
		}
		System.out.println();
	}

	public static boolean isSorted(Comparable[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			if (arr[i].compareTo(arr[i + 1]) > 0) {
				return false;
			}
		}
		return true;
	}

	public static <E> void testSort(String sortName, Sort concreteSort, E[] arr) {
		long startTime = System.nanoTime();

		concreteSort.sort((Comparable[]) arr);
		long endTime = System.nanoTime();

		System.out.println(sortName + " :" + (endTime - startTime) / 1000000000.0 + "s");
		return;
	}

	public static void testSort1(String sortName, Comparable[] arr) {
		try {
			Class clazz = Class.forName(sortName);
			Method method = clazz.getMethod("sort", Comparable[].class);
			Object[] params = new Object[] { arr };
			long startTime = System.currentTimeMillis();
			method.invoke(null, params);
			long endTime = System.currentTimeMillis();
			System.out.println(clazz.getSimpleName() + " : " + (endTime - startTime) + "ms");

			if (isSorted(arr)) {
				System.out.println("isSorted");
			} else {
				System.out.println("not Sorted");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public static Integer[] copyIntArray(Integer[] arr) {
		Integer[] temp = new Integer[arr.length];
		for (int i = 0; i < arr.length; i++) {
			temp[i] = arr[i];
		}
		return temp;
	}
}
